/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Ventanas.Administracion;

import com.asistencia.DAO.factory.FactoryDAO;
import com.asistencia.model.Modulo;
import com.asistencia.model.Turno;
import java.sql.Date;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author rfarias
 */
public class TurnosMANT extends javax.swing.JFrame {
    
    private Turno turtmp;

    /**
     * Creates new form TurnosMANT
     */
    public TurnosMANT() {

        initComponents();
        txtid.setVisible(false);
        llenaTabla();
        llenaCombo();
        
    }
    
    private void llenaTabla ()
    {
        DefaultTableModel dtm = new DefaultTableModel();
        Calendar c = Calendar.getInstance();
        String dia = Integer.toString(c.get(Calendar.DATE));
        String mes = Integer.toString(c.get(Calendar.MONTH)+1);
        String annio = Integer.toString(c.get(Calendar.YEAR));
        List<Turno> turnos = FactoryDAO.getInstance().getDataTur().findAll(annio+"-"+mes+"-"+dia, null);
        dtm.addColumn("Modulo");
        dtm.addColumn("Fecha Desde");
        dtm.addColumn("Fecha Hasta");
        dtm.addColumn("Hora Desde");
        dtm.addColumn("Hora Hasta");
        dtm.addColumn("id");
        
        
           
        
        for (Turno t : turnos)
        {
            dtm.addRow(new Object[]{t.getMod().getDescripcion(),t.getFecha_desde(),t.getFecha_hasta(),t.getHora_ini(),t.getHora_fin(),t.getId_turno()});
        }
        
        this.tblTurnosVig.setModel(dtm);
        TableColumn columna = tblTurnosVig.getColumn("id");
        columna.setMaxWidth(0);
        columna.setWidth(0);
        this.btnGuardar.setEnabled(false);
        this.jdcFechaFin.setEnabled(false);
        this.jdcFechaInicio.setEnabled(false);  
        this.txtHoraIni.setEnabled(false);
        this.txtHoraFin.setEnabled(false);
        this.cmbMod.setEnabled(false);
    }
    
    private void llenaCombo()
    {
        DefaultComboBoxModel cmbm = new DefaultComboBoxModel();
        List<Modulo> modulos =FactoryDAO.getInstance().getDataMod().findAll();
        for(Modulo m : modulos)
        {
            cmbm.addElement(m);
        }
        this.cmbMod.setModel(cmbm);
    
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
     * content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblTurnosVig = new javax.swing.JTable();
        jdcFechaInicio = new com.toedter.calendar.JDateChooser();
        jdcFechaFin = new com.toedter.calendar.JDateChooser();
        txtHoraIni = new javax.swing.JFormattedTextField();
        txtHoraFin = new javax.swing.JFormattedTextField();
        btnGuardar = new javax.swing.JButton();
        cmbMod = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        bntNuevo = new javax.swing.JButton();
        txtid = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("SITA - Administración");
        setBounds(new java.awt.Rectangle(200, 200, 0, 0));
        setIconImage(new ImageIcon(getClass().getResource("/Ventanas/icono.png")).getImage());

        tblTurnosVig.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Modulo", "Fecha desde", "Fecha hasta", "Hora Inicio", "Hora Fin"
            }
        ));
        tblTurnosVig.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblTurnosVigMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblTurnosVig);

        jdcFechaInicio.setEnabled(false);

        jdcFechaFin.setEnabled(false);

        txtHoraIni.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("HH:mm:ss"))));
        txtHoraIni.setToolTipText("Formato hh:mm:ss");
        txtHoraIni.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        txtHoraIni.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        txtHoraIni.setEnabled(false);

        txtHoraFin.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("HH:mm:ss"))));
        txtHoraFin.setEnabled(false);

        btnGuardar.setText("Guardar");
        btnGuardar.setEnabled(false);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        cmbMod.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbMod.setEnabled(false);

        jLabel1.setText("Fecha de Inicio");

        jLabel2.setText("Fecha de Fin");

        jLabel3.setText("Hora de Entrada");

        jLabel4.setText("Hora de Salida");

        jLabel5.setText("Módulo");

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel7.setText("Mantenedor de Turnos");

        jLabel6.setText("Turnos Vigentes");

        bntNuevo.setText("Nuevo");
        bntNuevo.setToolTipText("");

        txtid.setFocusable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jdcFechaInicio, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jdcFechaFin, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                                            .addComponent(jLabel2)))
                                    .addComponent(jLabel5)
                                    .addComponent(cmbMod, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(btnGuardar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtHoraIni))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel4)
                                        .addGap(18, 18, 18)
                                        .addComponent(txtid, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(bntNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtHoraFin, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(jScrollPane1)
                            .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addGap(5, 5, 5)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(txtid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jdcFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jdcFechaFin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtHoraIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtHoraFin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cmbMod))
                    .addComponent(btnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bntNuevo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblTurnosVigMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblTurnosVigMouseClicked
         Number fila = this.tblTurnosVig.getSelectedRow();
             //JOptionPane.showMessageDialog(null, fila);
          if (fila==null)
          {

          }
          else
          {
            int turnoid = (Integer) tblTurnosVig.getValueAt(fila.intValue(),5);
            turtmp = (Turno)FactoryDAO.getInstance().getDataTur().searchById(turnoid);
            this.jdcFechaInicio.setEnabled(true);
            this.jdcFechaInicio.setDate(turtmp.getFecha_desde());
            this.jdcFechaFin.setEnabled(true);
            this.jdcFechaFin.setDate(turtmp.getFecha_hasta());
            this.txtHoraIni.setEnabled(true);
            this.txtHoraIni.setText(turtmp.getHora_ini().toString());
            this.txtHoraFin.setEnabled(true);
            this.txtHoraFin.setText(turtmp.getHora_fin().toString());
            this.txtid.setText(String.valueOf(turtmp.getId_turno()));
            this.cmbMod.setEnabled(true);
            this.btnGuardar.setEnabled(true);
            
            
            
            this.cmbMod.getModel().setSelectedItem(turtmp.getMod());
          }
    }//GEN-LAST:event_tblTurnosVigMouseClicked

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        Turno trnsav=null;
        Calendar c = Calendar.getInstance();
        SimpleDateFormat shf = new SimpleDateFormat("HH:mm:ss");
        
        try {
            Time ti = new Time(shf.parse(this.txtHoraIni.getText()).getTime());
            Time tf = new Time(shf.parse(this.txtHoraFin.getText()).getTime());
            c.setTime(jdcFechaInicio.getDate());
            Date f1 = new Date(c.getTimeInMillis());
            c.setTime(jdcFechaFin.getDate());
            Date f2 = new Date(c.getTimeInMillis());
            trnsav = new Turno(f1,f2,ti,tf,(Modulo)this.cmbMod.getSelectedItem());
            trnsav.setId_turno(Integer.parseInt(this.txtid.getText()));
        } catch (ParseException ex) {
            Logger.getLogger(TurnosMANT.class.getName()).log(Level.SEVERE, null, ex);
        }        
        if (trnsav!=null)
        {
           Turno trnact = (Turno) FactoryDAO.getInstance().getDataTur().update(trnsav);
            if (trnact!=null)
            {
                JOptionPane.showMessageDialog(rootPane, "Se ha modificado el turno con exito", "Modificacion exitosa", JOptionPane.INFORMATION_MESSAGE);
                
            }
            else
            {
                JOptionPane.showMessageDialog(rootPane, "Ocurrio un fallo al modificar el turno", "Falla al modificar", JOptionPane.ERROR_MESSAGE);
            }
         llenaTabla();   
        }
        
    }//GEN-LAST:event_btnGuardarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TurnosMANT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TurnosMANT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TurnosMANT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TurnosMANT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TurnosMANT().setVisible(true);
            }
        });
    }

// <editor-fold defaultstate="collapsed" desc="Controles">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bntNuevo;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cmbMod;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private com.toedter.calendar.JDateChooser jdcFechaFin;
    private com.toedter.calendar.JDateChooser jdcFechaInicio;
    private javax.swing.JTable tblTurnosVig;
    private javax.swing.JFormattedTextField txtHoraFin;
    private javax.swing.JFormattedTextField txtHoraIni;
    private javax.swing.JTextField txtid;
    // End of variables declaration//GEN-END:variables
// </editor-fold>
}
